import { createRouter, createWebHistory } from "vue-router";

import Login from "@/views/Login.vue";
import MainBox from "@/views/MainBox.vue";
import RoutesConfig from "./config";
import { useRouteStore } from "../stores/index";
import { useUserStore } from "@/stores/userStore";

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox,
  },
  //mainbox的嵌套路由 后面根据权限动态添加
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

//全局前置守卫  每次路由跳转之前都会执行这一段回调函数
router.beforeEach((to, from, next) => {
  const firstRouteStore = useRouteStore();
  if (to.name === "login") {
    next();
  } else {
    // //未授权 (重定向到login)
    if (!localStorage.getItem("token")) {
      next({
        path: "/login",
      });
    } else {
      //如果授权(已经登陆过了)
      if (!firstRouteStore.isGetterRouter) {
        //删除所有嵌套路由
        router.removeRoute("mainbox");

        ConfigRouter();
        next({
          path: to.fullPath,
        });
      } else {
        next();
      }
    }
  }
});

const ConfigRouter = () => {
  if (!router.hasRoute("mainbox")) {
    router.addRoute({
      path: "/mainbox",
      name: "mainbox",
      component: MainBox,
    });
  }
  const firstRouteStore = useRouteStore();
  RoutesConfig.forEach((item) => {
    checkPermission(item) && router.addRoute("mainbox", item);
  });
  firstRouteStore.isGetterRouter = true;
};

const checkPermission = (item) => {
  const userStore = useUserStore();
  if (item.requiredAdmin) {
    return userStore.userInfo.is_admin === true;
  } else return true;
};

export default router;
